package com.wan.word;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.HeaderViewListAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.update.UmengUpdateAgent;
import com.wan.tool.DBManage;
import com.wan.tool.HttpUtils;
import com.wan.tool.InAndOut;
import com.wan.tool.Saying;
import com.wan.tool.Word;
import com.wan.widget.HoloCircularProgressBar;


import cn.domob.android.ads.DomobAdView;

public final class HomeActivity extends SherlockFragmentActivity {

    public static int ACTIVITY_DIALOG = 0;
    public static int ACTIVITY_SHOWWORD = 1;

    private SlidingMenu menu;

    public Handler handler = new Handler();


    private String showInCir;

    private InAndOut.TaskInfo taskInfo;

    //广告
    RelativeLayout mAdContainer;
    DomobAdView mAdview320x50;
    public static final String PUBLISHER_ID = "56OJzlS4uMnSLVtCGO";
    public static final String P_ID = "16TLm00lAceakY27DfO-vj4i";


    private void checkFirstUse(SharedPreferences shared) {
        Boolean fristLoginFlag = shared.getBoolean("fristlogin07", true);
        if (fristLoginFlag) {
            DBManage dbHelper = new DBManage(this);
            dbHelper.copyDatabase();
            SharedPreferences.Editor editer = shared.edit();
            editer.putBoolean("fristlogin07", false);
            editer.commit();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.word_home);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        UmengUpdateAgent.update(this);

        //菜单的初始化
        menuInit();

        //检查数据库
        checkFirstUse(getSharedPreferences("word07", MODE_PRIVATE));
        //对xml读写初始化
        InAndOut.init(getSharedPreferences("word07", MODE_PRIVATE));

        showByTaskInHome();

        //名言初始化
        sayingInit();

        mAdContainer = (RelativeLayout) findViewById(R.id.adcontainer);
        // 创建一个320x50的广告View
        mAdview320x50 = new DomobAdView(this, PUBLISHER_ID, P_ID, DomobAdView.INLINE_SIZE_320X50);
        mAdContainer.addView(mAdview320x50);


        Animation animation = AnimationUtils.loadAnimation(this,R.anim.home_circle_alpha);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                if("点击开始".equals(((TextView) findViewById(R.id.home_new_word_status_text)).getText())){
                    ((TextView) findViewById(R.id.home_new_word_status_text)).setText(showInCir);
                }else{
                    ((TextView) findViewById(R.id.home_new_word_status_text)).setText("点击开始");
                }
            }
        });
        findViewById(R.id.home_new_word_status_text).startAnimation(animation);
    }

    //根据taskinfo的信息展示主页的内容
    public void showByTaskInHome() {
        taskInfo = InAndOut.TaskInfo.getTaskInfo(0);
        if (taskInfo == null) {
            findViewById(R.id.home_noword_layout).setVisibility(View.VISIBLE);
            findViewById(R.id.home_task_layout).setVisibility(View.GONE);
            findViewById(R.id.home_noword_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    openTaskDialog();
                }
            });
        } else {
            findViewById(R.id.home_noword_layout).setVisibility(View.GONE);
            findViewById(R.id.home_task_layout).setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.home_task_name)).setText(taskInfo.getTaskName());
            ((TextView) findViewById(R.id.home_taskday_status)).setText("记忆天数：" + taskInfo.getTaskYijinDay() + "/" + taskInfo.getTaskNeedDay());
            ((TextView) findViewById(R.id.home_taskword_status)).setText(taskInfo.getTaskYijinWord() + "个/" + taskInfo.getTaskWordCount() + "个");

            //圆圈里显示的东西
            showInCir = "";
            if (taskInfo.getNowTimes() >= 1) {
                showInCir = taskInfo.getTodayNeedPei() + "/" + taskInfo.getTodayNeedPei() + "\n";
            }
            if (taskInfo.getNowTimes() >= 2) {
                showInCir += taskInfo.getTodayNeedPei() + "/" + taskInfo.getTodayNeedPei() + "\n";
            }
            if (taskInfo.getNowTimes() >= 3) {
                showInCir += taskInfo.getTodayNeedPei() + "/" + taskInfo.getTodayNeedPei();
            } else {
                showInCir += taskInfo.getTodayYiJinPei() + "/" + taskInfo.getTodayNeedPei();
            }

            ((TextView) findViewById(R.id.home_new_word_status_text)).setText(showInCir);

            ((TextView) findViewById(R.id.home_taskword_times)).setText("记忆次数：" + taskInfo.getNowTimes() + "/3");

            if (taskInfo.getTodayNeedPei() == 0) {
                ((HoloCircularProgressBar) findViewById(R.id.home_new_word_status_progressbar)).setProgress(1f);
            } else {
                if (taskInfo.isFinishToday()) {
                    ((HoloCircularProgressBar) findViewById(R.id.home_new_word_status_progressbar)).setProgress(1f);
                } else {
                    ((HoloCircularProgressBar) findViewById(R.id.home_new_word_status_progressbar)).setProgress((float) taskInfo.getTodayYiJinPei() / taskInfo.getTodayNeedPei());
                }
                findViewById(R.id.home_new_word_status_progressbar).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startNewWord();
                    }
                });
                findViewById(R.id.home_new_word_status_progressbar).setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                            ((HoloCircularProgressBar) view).setProgressBackgroundColor(getResources().getColor(R.color.prograss_blue));
                            ((HoloCircularProgressBar) view).setProgressColor(getResources().getColor(R.color.prograss_gray));
                        }
                        if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                            ((HoloCircularProgressBar) view).setProgressBackgroundColor(getResources().getColor(R.color.prograss_gray));
                            ((HoloCircularProgressBar) view).setProgressColor(getResources().getColor(R.color.prograss_blue));
                        }
                        return false;
                    }
                });
            }
            if (taskInfo.isFinishToday()) {
                findViewById(R.id.home_task_gotomorow).setVisibility(View.VISIBLE);
                if (taskInfo.isAllFinish()) {
                    ((Button) findViewById(R.id.home_task_gotomorow)).setText("全部完成，恭喜！");
                    findViewById(R.id.home_task_gotomorow).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Toast.makeText(view.getContext(), "恭喜！", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    ((Button) findViewById(R.id.home_task_gotomorow)).setText("背明天的");
                    findViewById(R.id.home_task_gotomorow).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            taskInfo.goTomorrow();
                            showByTaskInHome();
                        }
                    });
                }
            } else {
                findViewById(R.id.home_task_gotomorow).setVisibility(View.GONE);
            }
            Word nowWord = taskInfo.olnyGetNowWord();
            if (nowWord != null) {
                //这里下载第一个单词的发音
                HttpUtils.downOneWord(nowWord.num);
            }

        }
    }


    public void startNewWord() {
        Intent intent = new Intent(HomeActivity.this, ShowWordActivity.class);
        startActivityForResult(intent, ACTIVITY_SHOWWORD);
        overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
    }


    private void menuInit() {
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        menu.setShadowWidthRes(R.dimen.shadow_width);
        menu.setShadowDrawable(R.drawable.shadow);
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        menu.setFadeDegree(0.35f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        menu.setMenu(R.layout.word_menu);
        menu.setBehindScrollScale(0f);


        menu.findViewById(R.id.menu_create_task).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                openTaskDialog();
            }
        });

        menu.findViewById(R.id.menu_delTask).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(HomeActivity.this).setTitle("标题").setMessage("确定删除你的单词记录？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                InAndOut.delTask();
                                showByTaskInHome();
                            }
                        }).setNegativeButton("取消", null).show();
            }
        });

        menu.findViewById(R.id.menu_fb).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FeedbackAgent agent = new FeedbackAgent(HomeActivity.this);
                agent.startFeedbackActivity();
            }
        });

    }


    private void openTaskDialog() {
        menu.showContent();
        Intent intent = new Intent(HomeActivity.this, DialogActivity.class);
        startActivityForResult(intent, ACTIVITY_DIALOG);
        overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
    }


    private void sayingInit() {
        Saying saying = Saying.getOneSaying();
        if (saying != null) {
            TextView home_saying_en = (TextView) menu.findViewById(R.id.home_saying_en);
            TextView home_saying_cn = (TextView) menu.findViewById(R.id.home_saying_cn);
            home_saying_cn.setText(saying.cn);
            home_saying_en.setText(saying.en);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (menu.isMenuShowing()) {
                    menu.showContent();
                } else {
                    menu.showMenu();
                }
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ACTIVITY_DIALOG) {
            showByTaskInHome();
        } else {
            showByTaskInHome();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            String title = "要退出么？";
            Word word = Word.getOneRandomWord();
            new AlertDialog.Builder(HomeActivity.this).setTitle(title).setMessage(word.word)
                    .setPositiveButton(word.chinese, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            finish();
                            System.exit(0);
                        }
                    }).setNegativeButton("取消", null).show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


}
